package com.designoutput.manager
{
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.display.InteractiveObject;
	import flash.display.Stage;
	import flash.events.FocusEvent;
	import flash.text.TextField;

	public class FocusManager
	{
		private var _stage:Stage;
		private var _defaultFocus:InteractiveObject;
		
		public function FocusManager(stage:Stage)
		{
			_stage = stage;
			
			_stage.addEventListener(FocusEvent.MOUSE_FOCUS_CHANGE, focusChangeHandler, false, 0, true);
			_stage.addEventListener(FocusEvent.KEY_FOCUS_CHANGE, focusChangeHandler, false, 0, true);
		}
		
		public function get defaultFocus():InteractiveObject {
			return _defaultFocus;
		}
		public function set defaultFocus(value:InteractiveObject):void {
			_defaultFocus = value;
		}
		
		public function get focus():InteractiveObject {
			return _stage.focus;
		}
		
		public function setFocus(target:InteractiveObject):void {
			if(_stage.focus != target){
				trace("Focus change: ", _stage.focus, " -> ", target);
				_stage.focus = target;
			}
		}
		
		private function focusChangeHandler(e:FocusEvent):void {
			var oldFocus:InteractiveObject = e.currentTarget as InteractiveObject;
			var newFocus:InteractiveObject = e.relatedObject as InteractiveObject;

			e.preventDefault();
			
			if(!(newFocus is TextField))
				newFocus = defaultFocus;
			
			setFocus(newFocus);
		}
	}
}